/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cjava.system.bean.email;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Properties;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.cjava.system.bean.NavigationBean;
import org.cjava.system.model.ConfigEmail;
import org.cjava.system.service.interfac.IConfigEmailService;
import org.cjava.system.service.interfac.IPersonService;
import org.cjava.system.util.faces.FacesUtil;

/**
 *
 * @author user
 */
@ManagedBean
@SessionScoped
public class EMailBean implements Serializable {
private static final long serialVersionUID = 1L;
    @ManagedProperty("#{configEmailService}")
    IConfigEmailService configEmailService;
    @ManagedProperty("#{navigationBean}")
    NavigationBean navigationBean;
    @ManagedProperty("#{personService}")
    IPersonService personService;

    private ConfigEmail configEmail = new ConfigEmail();
    /////////////////////////////////////////////////////
    private String contentEmail;
    private String titleMessage;
    private Integer optionSend;
    private Integer totalSend;
    ///////////////////////////////////////////////////
    private String mailsForSend;
    private String messageConfirm;
    ////////////////////////////////////////////////////

    public void initValuesSendEmail() throws Exception {
        messageConfirm = "SIN ACCIÓN";
        String HQL = "select max(c.id) from ConfigEmail c";
        List<Integer> ids = configEmailService.listHQL(HQL);
        optionSend = null;
        if (ids.get(0) == null) {
            //NAVEGAR A LA ZONA DE CONFIGURACION
            navigationBean.setNavigationContent("./pages/content/email/configure_smtp_user.xhtml");
            configEmail = new ConfigEmail();
            FacesUtil.addMessage("ANTES DE ENVIAR CORREOS DEBE CONFIGURAR SMTP", null, FacesMessage.SEVERITY_WARN);
        } else {
            configEmail = configEmailService.getById(ids.get(0));
            contentEmail = "<div style=\"color: rgb(34, 34, 34); font-family: arial, sans-serif; font-size: 13px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: auto; word-spacing: 0px; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255);\"><div dir=\"ltr\"><div><strong><div style=\"text-align: left;\"><span style=\"font-weight: normal;\"><strong><contenido><br>-----------------------------------------------------------------------------------------<br>NOMBRE S&nbsp; | CJava : CARGO<br></contenido></strong></span></div></strong><div style=\"text-align: left;\">Oficina: Av. Arenales 395 oficina 403 &nbsp;</div></div><div><div style=\"text-align: left;\">&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Cercado de Lima &nbsp;- Lima 01 - Perú</div><div style=\"text-align: left;\">Teléfonos: (511) 433-6948</div></div><div><div style=\"text-align: left;\">Web:<span class=\"Apple-converted-space\">&nbsp;</span><a href=\"http://www.cjavaperu.com/\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\">http://www.cjavaperu.com</a></div><div style=\"text-align: left;\">Correo:<span class=\"Apple-converted-space\"> </span><a href=\"mailto:emaravi@cjavaperu.com\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\">CORREO@cjavaperu.com</a></div></div><div style=\"text-align: left;\"><br></div><div><font face=\"arial, sans-serif\"><b>Síguenos</b></font><b>&nbsp;en:</b>&nbsp;<a href=\"http://www.facebook.com/cjavaperu1\" target=\"_blank\" style=\"color: rgb(7, 77, 143);\"><img src=\"https://ci4.googleusercontent.com/proxy/dwlGZxzd_xuiJU14wDu04qxme65H6WoTTivARL3qpNw4P0Go4jDn3yaVB1-kJFKqwml1kyBqGf0D7KS517BfY5HvJA=s0-d-e1-ft#http://www.cjavaperu.com/uploads/facebook.png\"></a>&nbsp;<a href=\"http://twitter.com/@cjava_peru\" target=\"_blank\" style=\"color: rgb(7, 77, 143);\"><img src=\"https://ci4.googleusercontent.com/proxy/yg_fNFD26m8PswRUDjoi4dPQ6449XN6mNghybiDZOA7elmtXGsNiih5vPpemWYL9QATS_pa6sPpl2es1bCkMpyEd=s0-d-e1-ft#http://www.cjavaperu.com/uploads/twitter.png\"></a>&nbsp;<a href=\"https://plus.google.com/u/0/109384959685338323417\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\"><img src=\"https://ci5.googleusercontent.com/proxy/9GsvHDZ-XDcgZ0dEpg1OQ9fXGVAnC5ViRJSffU7yHcd3exAgoA6i9KfRQyzST7M8-6M4q8m68Ayo5DmLqA=s0-d-e1-ft#http://cjavaperu.com/logogoogleplus.png\"></a>&nbsp;<a href=\"http://pe.linkedin.com/pub/cjava-peru/43/524/726/\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\"><img src=\"https://ci5.googleusercontent.com/proxy/0gNkW9GBU2GCn8U3bHcgQ3c54cVARnRYEmWWdM3b5y9cHsA3RliMwj1V8r_KRfg2He5rs2B4eFp2=s0-d-e1-ft#http://cjavaperu.com/logolinked.png\"></a>&nbsp;<a href=\"http://cjavaperu.com/blog/\" target=\"_blank\" style=\"color: rgb(17, 85, 204);\"><img src=\"https://ci5.googleusercontent.com/proxy/KaxgsYY44ngckVpqI6eegD-nvovU85zPzaWah1V3UPcC8K5xUD2lFbhda8MCQFiS_857HhvQlY35Jzbk=s0-d-e1-ft#http://cjavaperu.com/logowordpress.png\"></a></div><div><br></div><div><div style=\"text-align: justify;\"><p style=\"margin-bottom: 0.0001pt;\"><i><span style=\"font-family: Arial, sans-serif;\">La información contenida en este mensaje y sus posibles documentos adjuntos es privada y confidencial y está dirigida únicamente a su destinatario/a. Si usted no es el/la destinatario/a original de este mensaje, por favor elimínelo. La distribución o copia de este mensaje no está autorizada.</span></i></p><p style=\"margin-bottom: 0.0001pt; line-height: 13.4pt;\"><i><span style=\"font-family: Arial, sans-serif;\">Tardas 5 segundos en imprimir este e-mail, el árbol que servirá para hacer el papel, tardará 7 años en crecer. No imprimas este mensaje si no es necesario.</span></i></p></div></div></div></div><br class=\"Apple-interchange-newline\">";

        }
    }

    public String emailsOfDB() throws Exception {
        String hql = "";
        String emails;
        List<String> perTemp = new ArrayList<String>();
        if (optionSend == 1) {
            //ENVIAR SOLO A SOCIOS
            hql = "select b.idPerson.email from BusinessAssociate b "
                    + "where b.idApertureAssociate.year="
                    + Calendar.getInstance().get(Calendar.YEAR);

            perTemp = personService.listHQL(hql);
        } else if (optionSend == 2) {
            //ENVIAR SOLO A EX-SOCIOS
            hql = "select b.idPerson.email from BusinessAssociate b "
                    + "where b.idApertureAssociate.year!="
                    + Calendar.getInstance().get(Calendar.YEAR);

            perTemp = personService.listHQL(hql);
        } else if (optionSend == 3) {
            //ENVIAR A TODOS
            hql = "select p.email from Person p";
            perTemp = personService.listHQL(hql);
        }
        if (perTemp.isEmpty()) {
            return null;
        } else {
            emails = perTemp.get(0);
            totalSend = perTemp.size();
            for (int i = 1; i < perTemp.size(); i++) {
                emails = emails + "," + perTemp.get(i);
            }
            System.out.println(emails);
            return emails;
        }

    }

    /**
     * Para configurar solo a algunas personas que se les envie el correo
     */
    public void sendEmailCustom() {
        String emailsSeparator = mailsForSend.trim().replace("\n", ",");
        System.out.println(emailsSeparator);
        final String username = configEmail.getUserEmail();
        final String password = configEmail.getPasswordEmail();

        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", configEmail.getHostName());
        //props.put("mail.smtp.port", configEmail.getPort());
        props.put("mail.smtp.port", "587");

        Session session = Session.getInstance(props,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
                });

        try {

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(configEmail.getUserEmail()));
//            message.setRecipients(Message.RecipientType.TO,
//                    InternetAddress.parse("dcondor.cjavaperu@gmail.com"));
            //CORREOS SEPARADOS POR COMAS.
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse(emailsSeparator, false));
            message.setSubject(titleMessage);

            message.setText(contentEmail, "utf-8", "html");

            Transport.send(message);
            messageConfirm = "MESAJES ENVIADOS CON ÉXITO...";
            FacesUtil.addMessage("Correos Enviados...", null, FacesMessage.SEVERITY_INFO);

        } catch (MessagingException e) {
            messageConfirm = "ERROR CON EL SERVIDOR SMTP";
            e.printStackTrace();
            FacesUtil.addMessage("Es posible que deba configurár su SMTP host Adecuadamente", null, FacesMessage.SEVERITY_WARN);

        }
    }

    public void sendEmail() throws Exception {

        System.out.println("Configuración por defecto");
        System.out.println("-------------------------");
        System.out.println("Host: " + configEmail.getHostName());
        System.out.println("user: " + configEmail.getUserEmail());
        System.out.println("Pass: " + configEmail.getPasswordEmail());
        System.out.println("Port: " + configEmail.getPort());
        //BUSCA EN LA BASE DE DATOS
        String emailsComplete = emailsOfDB();
        if (emailsComplete == null) {
            FacesUtil.addMessage("No encontro ningun correo", null, FacesMessage.SEVERITY_ERROR);
        } else {
            final String username = configEmail.getUserEmail();
            final String password = configEmail.getPasswordEmail();

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", configEmail.getHostName());
            //props.put("mail.smtp.port", configEmail.getPort());
            props.put("mail.smtp.port", configEmail.getPort());

            Session session = Session.getInstance(props,
                    new javax.mail.Authenticator() {
                        protected PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(username, password);
                        }
                    });

            try {

                MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(configEmail.getUserEmail()));
//            message.setRecipients(Message.RecipientType.TO,
//                    InternetAddress.parse("dcondor.cjavaperu@gmail.com"));
                //CORREOS SEPARADOS POR COMAS.
                message.setRecipients(Message.RecipientType.TO,
                        InternetAddress.parse(emailsComplete, false));
                message.setSubject(titleMessage);

                message.setText(contentEmail, "utf-8", "html");

                Transport.send(message);

                FacesUtil.addMessage(totalSend + " Correos Enviados...", null, FacesMessage.SEVERITY_INFO);
                messageConfirm = "CORREOS ENVIADOS...";
            } catch (MessagingException e) {
                e.printStackTrace();
                messageConfirm = "ERROR CON EL SERVIDOR SMTP...";
                FacesUtil.addMessage("Es posible que deba configurár su SMTP host Adecuadamente", null, FacesMessage.SEVERITY_WARN);
               

            }
        }

//        try {
//            Email email = new SimpleEmail();
//            email.setDebug(true);
//            //email.setHostName("panamera.websitewelcome.com");
//            email.setHostName(configEmail.getHostName());
//            email.setSmtpPort(configEmail.getPort());
//            email.setAuthenticator(new DefaultAuthenticator(configEmail.getUserEmail(), configEmail.getPasswordEmail()));
//            email.setSSLOnConnect(true);
//            ////////////////////////////////
//            email.setFrom(configEmail.getHostName());
//            email.setSubject(titleMessage);
//            email.setMsg(contentEmail);
//            String []emails = obtainEmails();
//            email.addTo(emails);
//            email.send();
//            ////////////////////////////////
//            System.out.println(contentEmail);
//            FacesUtil.addMessage("Los correos fueron enviados satisfactoriamente", null, FacesMessage.SEVERITY_INFO);
//        } catch (EmailException ex) {
//            System.out.println("No llego a su destino");;
//            FacesUtil.addMessage("Puede que su cuenta estea Baneado", null, FacesMessage.SEVERITY_ERROR);
//            FacesUtil.addMessage("Configure otro correo para el envio...", null, FacesMessage.SEVERITY_INFO);
//            Logger.getLogger(EMailBean.class.getName()).log(Level.SEVERE, null, ex);
//        } catch (Exception ex) {
//            System.out.println("Error en la consulta");
//            Logger.getLogger(EMailBean.class.getName()).log(Level.SEVERE, null, ex);
//        }
    }

    public void saveOrUpdateConfigEmail() throws Exception {
        if (configEmail.getId() == null) {
            configEmailService.save(configEmail);
            configEmail = new ConfigEmail();
            FacesUtil.addMessage("Guardado con éxito...", null, FacesMessage.SEVERITY_INFO);
        } else {
            configEmailService.update(configEmail);
            configEmail = new ConfigEmail();
            FacesUtil.addMessage("Actualizado con éxito...", null, FacesMessage.SEVERITY_INFO);
        }
    }

    public void setConfigEmailService(IConfigEmailService configEmailService) {
        this.configEmailService = configEmailService;
    }

    public ConfigEmail getConfigEmail() {
        return configEmail;
    }

    public String getMessageConfirm() {
        return messageConfirm;
    }

    public void setMessageConfirm(String messageConfirm) {
        this.messageConfirm = messageConfirm;
    }

    public void setConfigEmail(ConfigEmail configEmail) {
        this.configEmail = configEmail;
    }

    public void setNavigationBean(NavigationBean navigationBean) {
        this.navigationBean = navigationBean;
    }

    public String getContentEmail() {
        return contentEmail;
    }

    public void setContentEmail(String contentEmail) {
        this.contentEmail = contentEmail;
    }

    public Integer getOptionSend() {
        return optionSend;
    }

    public void setOptionSend(Integer optionSend) {
        this.optionSend = optionSend;
    }

    public void setPersonService(IPersonService personService) {
        this.personService = personService;
    }

    public String getTitleMessage() {
        return titleMessage;
    }

    public void setTitleMessage(String titleMessage) {
        this.titleMessage = titleMessage;
    }

    public String getMailsForSend() {
        return mailsForSend;
    }

    public void setMailsForSend(String mailsForSend) {
        this.mailsForSend = mailsForSend;
    }

}
